
#include "CC_Timer_Handler.h"
#include "ICC_Timer_Handler.h"


CCTimer::~CCTimer()
{
	this->StopTimer();
}

void CCTimer::StartTimer(long millisecond, bool isloop)
{
	this->_interval = millisecond;
	this->_isloop = isloop;
	CCReactor::Instance()->RegistTimer(this,millisecond);
}


void CCTimer::StartTimer2(long ssecond, bool isloop)
{
	return StartTimer(ssecond*1000,isloop);
}

void CCTimer::StopTimer(void)
{
	CTimerObject::DisableTimer();
	this->_isloop=false;
}

void CCTimer::SetTimeEventObj(TimerOutEvent * obj, int id)
{
	_TimeEvent=obj;
	_nId=id;
}


void CCTimer::TimerNotify(void)
{
	if (_isloop)
	{
		StartTimer(_interval, _isloop);
	}

	if (_TimeEvent)
		_TimeEvent->ProcessOnTimerOut(_nId);

}


BYTimerOject::~BYTimerOject()
{
	for (BYTimerList::iterator it=m_nTimerController.begin(); it!=m_nTimerController.end(); ++it)
	{
		CCTimer* pTimer = it->second;
		pTimer->StopTimer();
		delete pTimer;
	}
	m_nTimerController.clear();
}

int BYTimerOject::StartTimer(int TimerID, long second, bool isloop)
{
	CCTimer* pTimer = GetTimer(TimerID);
	pTimer->StopTimer();
	pTimer->StartTimer2(second, isloop);
	return 0;
}

int BYTimerOject::StartTimerMillisecond(int TimerID, long millisecond, bool isloop)
{
	CCTimer* pTimer = GetTimer(TimerID);
	pTimer->StopTimer();
	pTimer->StartTimer(millisecond, isloop);
	return 0;
}

int BYTimerOject::StopTimer(int TimerID)
{
	CCTimer* pTimer = GetTimer(TimerID);
	if(pTimer)
	{
		pTimer->StopTimer();
	}
	return 0;
}

int BYTimerOject::ProcessOnTimerOut(int TimerId)
{
	return OnBYTimeOut(TimerId);
}


CCTimer* BYTimerOject::GetTimer(int TimerID)
{
	BYTimerList::iterator it = m_nTimerController.find(TimerID);
	if(it != m_nTimerController.end())
		return it->second;
	else
	{
		CCTimer* pTimer = new CCTimer();
		pTimer->SetTimeEventObj(this, TimerID);
		m_nTimerController[TimerID] = pTimer;
		return pTimer;
	}
}

void BYTimerOject::DelTimer(int TimerID)
{
	BYTimerList::iterator it = m_nTimerController.find(TimerID);
	if(it != m_nTimerController.end())
	{
		CCTimer* pTimer = it->second;
		pTimer->StopTimer();
		delete pTimer;
		m_nTimerController.erase(it);
	}
}
